package org.mozhu.mboot.core.config;

import org.springframework.core.env.*;

import java.util.*;
import java.util.stream.Collectors;

@SuppressWarnings("unchecked")
public class PropertiesUtils {

    public static Set<String> getKeys(PropertySources propertySources) {
        Set<String> keys = new HashSet<>();
        for (PropertySource<?> propertySource : propertySources) {
            if (propertySource instanceof EnumerablePropertySource) {
                String[] propertyNames = ((EnumerablePropertySource) propertySource).getPropertyNames();
                if (propertyNames != null) {
                    keys.addAll(Arrays.asList(propertyNames));
                }
            } else if (propertySource.getSource() instanceof ConfigurableEnvironment) {
                keys.addAll(getKeys(((ConfigurableEnvironment) propertySource.getSource()).getPropertySources()));
            }
        }
        return keys;
    }

    public static Set<String> getKeys(PropertySources properties, String prefix) {
        return getKeys(properties).stream().filter((key) -> key.startsWith(prefix)).collect(Collectors.toSet());
    }

    public static List<String> getList(PropertyResolver resolver, String key) {
        if (!resolver.containsProperty(key)) {
            return null;
        }
        String stringValue = resolver.getProperty(key);
        List<String> values = new ArrayList<String>();
        values.addAll(Arrays.asList(stringValue.split(",")));
        return values;
    }
}
